<?php
/**
 * Created by PhpStorm.
 * User: 刘海平（785313152）
 * Date: 2019/4/4
 * Time: 10:18
 * Message: 对未来没概念，也不想有概念，脑子里只关心汤面会不会太咸！
 */

namespace app\index\controller;


use app\common\controller\IndexBase;
use app\common\model\ExpLog;
use app\common\model\IntegralLog;
use app\common\model\Message;
use app\common\model\User;
use app\index\model\Comment;
use app\common\model\Topic;
use think\Session;

class Travel extends IndexBase
{
    protected function _initialize()
    {
        parent::_initialize();
        $this->assign('title_head','活动天地');
    }

    public function index(){
        $list = model('Topic')->where(['status'=>1])->order('appreciate desc,comment desc,add_time desc')->limit(10)->select();
        $banner = model('Ads')->where('nid=2')->select();
        $this->assign('banner',$banner);
        $this->assign('list',$list);
        return $this->fetch();
    }

    //旅游攻略
    public function strategy(){
        $topic = new Topic();
        $type= input('type')?input('type'):1;//话题类型1旅途攻略2旅途问答3结伴出游4旅途分享
        $label = input('label')?input('label'):1;
        $title = input('title');
        $title ? $where['title'] = ['like', "%{$title}%"] : '';
        $where['type']=$type;
        if($label!=1){
            $where['author'] = Session::get('user_info')['userid'];
        }
        $status = input('status');
        //状态筛选（主要在旅途问答中）
        if($status){
            $where['status']=$status;
        }else{
            $status = 'all';
        }
        $this->assign('status',$status);
        $list = $topic->where($where)->order('status asc,comment desc,add_time desc')->limit(5)->select();
        $this->assign('list',$list);
        $this->assign('type',$type);
        $this->assign('label',$label);
        //旅途分享||旅途攻略
        if($type==1){
            $this->assign('topic_name','攻略');
            $this->assign('title_head','活动攻略');
            return $this->fetch('strategy');
        }
        //旅途问答
        if($type==2){
            return $this->fetch('faq');
        }
        //结伴出游
        if($type==3){
            return $this->fetch('mate');
        }
        //旅途分享||旅途攻略
        if($type==4){
            $this->assign('topic_name','分享');
            $this->assign('title_head','活动分享');
            return $this->fetch('strategy');
        }

        return $this->fetch('strategy');
    }


    public function strategy_page(){
        $topic = new Topic();
        $label = input('label')?input('label'):1;
        $type = input('type')?input('type'):1;
        $where['type']=$type;
        $status = input('status');
        if($status!='all'){
            $where['status']=$status;
        }
        if($label!=1){
            $where['author'] = Session::get('user_info')['userid'];
        }
        $page = input('page');
        $title = input('title');
        $title ? $where['title'] = ['like', "%{$title}%"] : '';
        $list = $topic->where($where)->order('status asc,comment desc,add_time desc')->page($page,5)->select();
        exit(json_encode($list));
    }
    //发布
    public function publish_strategy(){
        $type = input('type')?input('type'):1;
        $this->assign('type',$type);
        $topic = new Topic();
        if($this->request->isAjax()){
            $data = input('post.');
            $data['add_time'] = date('Y-m-d H:i:s');
            $data['type'] =$type;
            $data['travel_cate'] = input('travel_cate');
            $data['author'] = Session::get('user_info')['userid'];
            $data['author_name'] = Session::get('user_info')['name'];
            $data['user_head'] = Session::get('user_info')['avatar'];
            //发布提问是预判断积分是否充足
            if($type==2){
                $user_info = model('User')->find(['user_id'=>session('user_info')['userid']]);
                $data['reward_integeal'] = input('reward_integral');
                if($user_info['integral']<($user_info['freeze_integral']+$data['reward_integeal'])){
                    $this->error('您的积分不足，请检查积分余额以及冻结积分');
                }
                model('User')->where(['user_id'=>session('user_info')['userid']])->setInc('freeze_integral',$data['reward_integeal']);
            }
            $res = $topic->validate(true)->allowField(true)->save($data);
            //发布话题获取经验值
            $exp = $this->roule['topic_exp'];
            $integral = $this->roule['topic_integral'];
            $user = new User();
            if($res!==false){
                $msg = '发布成功';
                //提问不获取积分和经验
                if($type!=2){
                    if($exp>0){
                        //发布话题获取经验
                        $catche = $user->put_exp(1,$exp,$topic->id);
                        if($catche) {
                            $msg.= ' 获得' . $exp . '经验';
                        }
                    }
                    if($integral>0){
                        $integral_catche = $user->put_integral(1,$integral,$topic->id);
                        if($integral_catche) {
                            $msg.= ' 获得' . $integral . '积分';
                        }
                    }
                }
                $this->success($msg,'strategy?type='.$type);
            }else{
                $this->error('发布失败');
            }
        }
        if($type==2){
            $this->assign('title_head','发布提问');
            return $this->fetch('publish_faq');
        }
        if($type==1||$type==4){
            $this->assign('title_head','发布话题');
            return $this->fetch();
        }
    }

    public function close_topic(){
        $id = input('topic_id');
        $topic = model('Topic')->find($id);
        $data['id'] = $id;
        $data['status'] = 2;
        if(Session::get('user_info')['userid']==$topic['author']){
            if(model('Topic')->isUpdate(true)->save($data)){
                $this->success('话题已关闭');
            }else{
                $this->error('话题关闭失败，请确认话题已经关闭后联系管理员');
            }
        }else{
            $this->error('权限不足，请关闭属于您自己发布的话题');
        }
    }
    //详情
    public function strategy_detail(){
        $id = input('id');
        $topic = new Topic();
        $rows = $topic->find($id);
        $this->assign('rows',$rows);
        $collect = model('appreciate')->where(['user_id'=>\session('user_info')['userid'],'type'=>2,'topic_id'=>$rows['id']])->find();
        $apprecaite = model('appreciate')->where(['user_id'=>\session('user_info')['userid'],'type'=>1,'topic_id'=>$rows['id']])->find();
        $this->assign('collect',$collect);
        $this->assign('appreciate',$apprecaite);
        if($rows['type']==2){
            return $this->fetch('faq_detail');
        }
        if($rows['type']==3){
            $this->redirect(url('mate_detail',['id'=>$rows['id']]));
        }
        return $this->fetch();
    }

    public function publish_comment(){
        if($this->request->isAjax()){
            //话题关闭后，无法进行评论操作
            $topic = model('Topic')->find(input('topic_id'));
            if($topic['status']==2){
                $this->error('话题已经关闭，无法进行评论');
            }
            $data['topic_id'] = input('topic_id');
            $data['content']= input('content');
            $data['user_id'] = Session::get('user_info')['userid'];
            $data['user_name'] = Session::get('user_info')['name'];
            $data['user_head'] = Session::get('user_info')['avatar'];
            $data['add_time'] = date('Y-m-d H:i:s');
            //评论是否是回复用户评论
            $data['recomment'] = input('recomment');
            //推送消息,非本人评论
            if($topic['author']!==Session::get('user_info')['userid']){
                $send_message =true;
            }
            $comment = new Comment();
            $result = $comment->validate(true)->allowField(true)->save($data);
            //评论完成后评论数+1
            $topic = new Topic();
            $topic->where(['id'=>$data['topic_id']])->setInc('comment');
            $topic_info = $topic->get($data['topic_id']);
            //评论经验值
            $exp = $this->roule['comment_exp'];
            $integral = $this->roule['comment_integral'];
            $user = new User();
            if($result!==false){
                if($send_message){
                    $message = new Message();
                    $message->send_message(session('user_info')['userid'],'您发布的话题，有新的评论',2,url('travel/strategy_detail',['id'=>$data['topic_id']]));
                }
                $msg = '评论成功';
                if(($topic_info['type']==1)||($topic_info['type']==4)){
                    if($exp>0){
                        $put_exp = $user->put_exp(2,$exp,$comment->id);
                        //评论获取经验
                        if($put_exp) {
                            $msg.= '获得' . $exp . '经验';
                        }
                    }
                    if($integral>0){
                        $integral_catche =$user->put_integral(2,$integral,$comment->id);
                        if($integral_catche) {
                            $msg.= ' 获得' . $integral . '积分';
                        }
                    }
                }
                $this->success($msg);
            }else{
                $this->error('评论失败');
            }
        }
    }
    //采纳答案
    public function adopt(){
        $comment_id = input('comment_id');
        $topic_id = input('topic_id');
        //采纳并关闭话题
        $topic = new Topic();
        $user = new User();
        $comment = new Comment();
        $caina = $topic->isUpdate(true)->save(['id'=>$topic_id,'answer_id'=>$comment_id,'status'=>2]);
        if($caina!==false){
            //先减分
            $topic_info = $topic->find($topic_id);
            $sql = "UPDATE hs_user set integral=integral-".$topic_info['reward_integral'].", freeze_integral=freeze_integral-".$topic_info['reward_integral']." WHERE `user_id`='".$topic_info['author']."'";
            $integral_log = new IntegralLog();
            $user->query($sql);
            //再加分
            $comment_info = $comment->find($comment_id);
            $user->where(['user_id'=>$comment_info['user_id']])->setInc('integral',$topic_info['reward_integral']);
            $list =[
                ['type'=>3,'user_id'=>$comment_info['user_id'],'integral'=>$topic_info['reward_integral'],'add_time'=>date('Y-m-d H:i:s'),'relation_id'=>$topic_id],
                ['type'=>3,'user_id'=>$topic_info['author'],'integral'=>'-'.$topic_info['reward_integral'],'add_time'=>date('Y-m-d H:i:s'),'relation_id'=>$topic_id],
            ];
            $integral_log->saveAll($list);
            $this->success('采纳成功');
        }
        $this->error('提交失败，请确认话题已关闭');
    }

    public function mate(){
        $qyery_type = input('query_type')?input('query_type'):1;
        $this->assign('query_type',$qyery_type);
        return $this->fetch();
    }

    public function get_mate_list(){
        $query_type = input('query_type')?input('query_type'):1;
        $title = input('title');
        if($title){
            $where['title'] = ['like','%'.$title.'%'];
        }
        if($query_type==2){
            $where['author'] = Session::get('user_info')['userid'];
        }
        if($query_type==3){
            $topic_id_list = model('appreciate')->where(['type'=>3,'user_id'=>\session('user_info')['userid']])->column('topic_id');
            $where['id'] =['in',$topic_id_list];
        }
        $page = input('page')?input('page'):1;
        $where['type']=3;
        $topic = new Topic();
        $list = $topic->where($where)->order('status asc,appreciate desc,add_time desc')->page($page,5)->select();
        $this->assign('list',$list);
        return $this->fetch();
    }

    public function publish_mate(){
        if($this->request->isAjax()){
            $topic = new Topic();
            $data =input('post.');
            $data['author'] = Session::get('user_info')['userid'];
            $data['author_name'] = Session::get('user_info')['name'];
            $data['user_head'] = Session::get('user_info')['avatar'];
            $data['add_time'] = date('Y-m-d H:i:s');
            $data['type']=3;
            $res = $topic->validate(true)->allowField(true)->save($data);
            //发布话题获取经验值
            $exp = $this->roule['topic_exp'];
            $integral = $this->roule['topic_integral'];
            $user = new User();
            if($res!==false){
                $msg = '发布成功';
                /*发布结伴是否获取经验
                if($exp>0){
                    //发布话题获取经验
                    $catche = $user->put_exp(1,$exp,$topic->id);
                    if($catche) {
                        $msg.= ' 获得' . $exp . '经验';
                    }
                }
                if($integral>0){
                    $integral_catche = $user->put_integral(1,$integral,$topic->id);
                    if($integral_catche) {
                        $msg.= ' 获得' . $integral . '积分';
                    }
                }
                */
                $this->success($msg,'mate');
            }else{
                $this->error('发布失败');
            }
        }
        return $this->fetch();
    }


    public function mate_detail(){
        $id = input('id');
        $topic = new Topic();
        $rows = $topic->find($id);
        $this->assign('rows',$rows);
        $collect = model('appreciate')->where(['user_id'=>\session('user_info')['userid'],'type'=>2,'topic_id'=>$rows['id']])->find();
        $apprecaite = model('appreciate')->where(['user_id'=>\session('user_info')['userid'],'type'=>1,'topic_id'=>$rows['id']])->find();
        $sign_info = model('appreciate')->where(['user_id'=>\session('user_info')['userid'],'type'=>3,'topic_id'=>$rows['id']])->find();
        $this->assign('collect',$collect);
        $this->assign('appreciate',$apprecaite);
        $this->assign('sign_info',$sign_info);
        return $this->fetch();
    }

    public function sign_mate(){
        $topic_id  = input('topic_id');
        $do_sign = input('do_sign');
        //判断是否已经报名
        $appreciate = new \app\common\model\Appreciate();
        $topic = new Topic();
        $topic_info = $topic->find($topic_id);
        if($topic_info['status']!=1){
            $this->error('活动已经成行，无法再进行操作');
        }
        if(strtotime($topic_info['end_time'])<time()){
            $this->error('活动已经结束，无法再进行操作');
        }
        $sign_info = $appreciate->withTrashed()->where(['user_id'=>\session('user_info')['userid'],'type'=>3,'topic_id'=>$topic_id])->find();
        if($do_sign==1){
            if($topic_info['number']==$topic_info['sign_number']){
                $this->error('报名人数已达上限');
            }
            if($sign_info){
                if(!$sign_info['delete_time']){
                    $this->error('您已经成功报名该活动');
                }
                $isupdate = true;
                $data['delete_time']=null;
                $data['id'] =$sign_info['id'];
            }
            $data['user_id'] =  \session('user_info')['userid'];
            $data['type'] =3;
            $data['add_time'] = date('Y-m-d H:i:s');
            $data['topic_id']=$topic_id;
            $sign = $appreciate->isUpdate($isupdate)->save($data);
            if($sign!==false){
                $topic->where('id','=',$topic_id)->setInc('sign_number');
                $this->success('报名成功');
            }else{
                $this->error('报名失败');
            }
        }else{
            if($sign_info&&$sign_info['delete_time']){
                $this->error('您已经取消报名');
            }
            $sign = $appreciate::destroy($sign_info['id']);
            if($sign!==false){
                $topic->where('id','=',$topic_id)->setDec('sign_number');
                $this->success('取消报名成功');
            }
            $this->error('取消报名失败');
        }
        $this->error('请求失败');
    }

    public function get_sign_list(){
        $topic_id = input('topic_id');
        $list = model('Appreciate')->where(['type'=>3,'topic_id'=>$topic_id])->select();
        foreach ($list as $v){
            $res = get_user_info($v['user_id']);
           // if($res['errcode']==0){
                $user_list[] = $res['name'];
           // }
        }
        return $user_list;
    }

    //修改活动人数
    public function change_number(){
        $topic_id = input('topic_id');
        $number = input('number');
        $topic =new Topic();
        $info = $topic->find($topic_id);
        if(\session('user_info')['userid']!=$info['author']){
            return ajax_return(0,'此操作需要话题发起人操作');
        }
        if($info['sign_number']>$number){
            return ajax_return(0,'活动人数不能小于当前报名的人数');
        }
        $data['number']= $number;
        if($topic->where(['id'=>$topic_id])->update($data)!==false){
            return ajax_return(1,'修改成功');
        }else{
            return ajax_return(0,'修改失败');
        }
    }
}